package com.changgou.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.changgou.goods.feign.SkuFeign;
import com.changgou.goods.pojo.Sku;
import com.changgou.search.dao.ESManagerMapper;
import com.changgou.search.pojo.SkuInfo;
import com.changgou.search.service.ESManagerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

/**
 * @Description:
 * @Version: V1.0
 */
@Service
public class ESManagerServiceImpl implements ESManagerService{

    @Autowired
    private ElasticsearchTemplate elasticsearchTemplate;
    @Autowired
    private SkuFeign skuFeign;
    @Autowired
    private ESManagerMapper esManagerMapper;
    @Override
    public void createIndexAndMapping() {
        //创建索引
        elasticsearchTemplate.createIndex(SkuInfo.class);
        //创建映射
        elasticsearchTemplate.putMapping(SkuInfo.class);
    }

    @Override
    public void importAll() {
        //查询sku集合
        List<Sku> skuList = skuFeign.findSkuListBySpuId("all");
        if (skuList==null || skuList.size()<=0){
            throw new RuntimeException("没有查询到数据，无法导入索引库");
        }
        String s = JSON.toJSONString(skuList);
        List<SkuInfo> skuInfoList = JSON.parseArray(s, SkuInfo.class);
        for (SkuInfo skuInfo : skuInfoList) {
            //将规格信息转换成map
            Map specMap = JSON.parseObject(skuInfo.getSpec(), Map.class);
            skuInfo.setSpecMap(specMap);
        }
        esManagerMapper.saveAll(skuInfoList);
    }

    @Override
    public void importDataToESBySpuId(String spuId) {
        List<Sku> skuListBySpuId = skuFeign.findSkuListBySpuId(spuId);
        if (skuListBySpuId==null || skuListBySpuId.size()<=0){
            throw new RuntimeException("没有查询到数据，无法导入索引库");
        }
        String s = JSON.toJSONString(skuListBySpuId);
        List<SkuInfo> skuInfoList = JSON.parseArray(s, SkuInfo.class);
        for (SkuInfo skuInfo : skuInfoList) {
            Map specMap = JSON.parseObject(skuInfo.getSpec(), Map.class);
            skuInfo.setSpecMap(specMap);
        }
        esManagerMapper.saveAll(skuInfoList);
    }

    @Override
    public void deleteBySpuId(String spuId) {
        List<Sku> skuListBySpuId = skuFeign.findSkuListBySpuId(spuId);
        if (skuListBySpuId==null || skuListBySpuId.size()<=0){
            throw new RuntimeException("没有查询到数据，删除索引库");
        }
        for (Sku sku : skuListBySpuId) {
            esManagerMapper.deleteById(Long.parseLong(sku.getId()));
        }

    }
}
